<script>
  import tree from '@/mixins/tree/index.js'
  import AjaxStore from '@/utils/store/proxyAjax'
  import store from './store.js'
  import { validateNumber } from '@/utils/validate'

	export default {
    name: 'function',
	  mixins: [tree, store],
	  data() {
      const validateOrderNo = (rule, value, callback) => {
        if (value && !validateNumber(value)) {
          callback(new Error('请输入正整数'))
        } else {
          callback()
        }
      };
	    return {
        editPid: '',
        pidLabel: '',
        funName: '',

        labelWidth: '100px',

        tree: {
          width: "280",
          accordion: false,
          isShowHeader: true,
          treeMenuButtonList: this.treeMenuBtns,
          treeOperateButtonList: this.treeOperateBtns,
          search: {
            searchKey: 'nodeName'
          },
          showCheckbox: false,
          selectTree: {},
          nextNodeKey: 'node',
          idKey: 'funId',
          title: '权限功能',
          getNextChildNode: this.getNextNode,
          delNode: this.delNode
        },

	      nodeIdKey: 'id',
	      nodeLabelKey: 'text',
	      pidKey: 'pid',
	      idKey: 'funId',
        labelKey: 'funName',
        currentNode: null,
	      panelType: '',

	      addNodeInfoUrl: '/v1/sys/function/add',
	      updateNodeInfoUrl: '/v1/sys/function/update',
	      getNextNodeUrl: '/v1/sys/function/findNextChildNodeTree',
	      delNodeUrl: '/v1/sys/function/deleteNode',
	      getNodeInfoUrl: '/v1/sys/function/findById',
	      store: new AjaxStore({
	        url: '/v1/sys/function/query'
	      }),

        formPanel: {
          add: {
            model: {
              "projectId": '',
              "funId": '',
              "funName": '',
              "funType": '',
              "location": '',
              "pid": '',
              "orderNo": '',
              "logFlag": 0,
              "icon": '',
              "version": '',
              "remark": '',
              "fullPath": ''
            },
            fields: [
              { label: '父功能', prop: 'pid', anchor: 24, xType: 'SelectTree.TREE', ref: 'addPid', relatedFields:['addFunPath'],
                treeParams: {
                  get: {
                    url: "/v1/sys/function/findNextChildNodeTree",
                    nextNodeKey: "node",
                    idKey: "id"
                  }
                },
                valueToLabelParams: {
                  url: '/v1/dataProvider/getFunName',
                  idKey: 'funId'
                },
                on: {
                  'visible-change': val => val && this.$refs.addForm.$refs.addPid.reload()
                }
              },
              // { label: '父功能', prop: 'pid', xType: 'SelectTree.tree', url: '/v1/sys/group/findNextChildNodeTree', anchor: 24},
              { label: '功能类型', prop: 'funType', xType: 'SelectCode.FUN_TYPE', placeholder: '输入功能类型', anchor: 24},
              { label: '功能编码', prop: 'funId', placeholder: '输入功能编码', anchor: 24},
              { label: '功能名称', prop: 'funName', placeholder: '输入功能名称', anchor: 24,
                on: {
                  input: (val) => {
                    this.funName = val
                    if (!this.formPanel.add.model.pid) {
                      this.formPanel.add.model.fullPath = this.filterArray([this.funName]).join('/')
                    } else {
                      const selectPidLabel = this.$refs.addForm.$refs.addPid.selectedLabel
                      this.formPanel.add.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, selectPidLabel), this.funName]).join('/')
                    }
                  }
                }
              },
              { label: '链接', prop: 'location', placeholder: '输入链接', anchor: 24},
              { label: '排序号', prop: 'orderNo', placeholder: '输入排序号', anchor: 24},
              { label: '是否记日志', prop: 'logFlag', xType: 'switch', anchor: 24, "active-value": 1, "inactive-value": 0},
              // { label: '是否记日志', prop: 'logFlag', xType: 'SelectCode.IF', placeholder: '输入是否记日志', anchor: 24},
              { label: '图标', prop: 'icon', placeholder: '输入图标', anchor: 24},
              { label: '版本', prop: 'version', placeholder: '输入版本', anchor: 24},
              { label: '备注', prop: 'remark', placeholder: '输入备注', anchor: 24},
              { label: '全路径', prop: 'fullPath', anchor: 24, readonly: true, style: 'border: 0;', ref: 'addFunPath',
                on: {
                  'el.form.update': (val, ctx, origin, form) => {// 值,当前组件,关联组件
                    if (form.model.pid) {
                      this.getNodeInfo({funId: form.model.pid}).then(({ success, data }) => {
                        if ( success && data.fullPath) {
                          // 获取上级机构全路径
                          this.fullPath = data.fullPath
                          this.formPanel.add.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, origin.selectedLabel), form.model.funName]).join('/')
                        }
                      })
                    } else {
                      form.model.fullPath = this.filterArray([form.model.funName]).join('/')
                    }
                  }
                }
              }
            ],
		        rules: {
              "funId": [{ required: true, message: '请输入功能编码', trigger: 'blur' }],
              "funName": [{ required: true, message: '请输入功能名称', trigger: 'blur' }],
              "funType": [{ required: true, message: '请输入功能类型', trigger: 'blur' }],
              "orderNo": [{ validator: validateOrderNo, trigger: 'blur' }]
              // "logFlag": [{ required: true, message: '请输入是否记日志', trigger: 'blur' }],
            },
            title: '新增权限功能',
            type: 'ADD',
            ref: 'addForm',
            submitBtnList: this.addBtns
            },
          edit: {
            model: {
              "projectId": '',
              "funId": '',
              "funName": '',
              "funType": '',
              "location": '',
              "pid": '',
              "orderNo": '',
              "logFlag": 0,
              "icon": '',
              "version": '',
              "remark": '',
              "fullPath": ''
            },
            fields: [
              { label: '父功能', prop: 'pid', anchor: 24, xType: 'SelectTree.TREE', ref: 'editPid', relatedFields:['editFunPath'],
                on:{
                  'update': (val, vnode, form)=>{
                    const selfId = this.editPid
                    const $tree = vnode.$refs.tree
                    const path = $tree.getNodePath(val) || []
                    for(let i = 0, len = path.length; i<len; i++){
                      if(selfId === path[i]['id']){
                        form.model.pid = ''
                        this.$message({
                          type: 'error',
                          message: '组织机构上级机构不能选择自身或自己的子节点！'
                        })
                        break
                      }
                    }
                  },
                  'visible-change': val => val && this.$refs.editForm.$refs.editPid.reload()
                },
                // 下拉树参数
                treeParams: {
                  get: {
                    url: "/v1/sys/function/findNextChildNodeTree",
                    nextNodeKey: "node",
                    idKey: "id"
                  }
                },
                valueToLabelParams: {
                  url: '/v1/dataProvider/getFunName',
                  idKey: 'funId'
                }
              },
              // { label: '父功能', prop: 'pid', xType: 'SelectTree.tree', url: '/v1/sys/group/findNextChildNodeTree', anchor: 24},
              { label: '功能类型', prop: 'funType', xType: 'SelectCode.FUN_TYPE', placeholder: '输入功能类型', anchor: 24},
              { label: '功能编码', prop: 'funId', placeholder: '输入功能编码', anchor: 24, disabled: true},
              { label: '功能名称', prop: 'funName', placeholder: '输入功能名称', anchor: 24,
                on: {
                  input: (val) => {
                    this.funName = val
                    if (!this.formPanel.edit.model.pid) {
                      this.formPanel.edit.model.fullPath = this.filterArray([this.funName]).join('/')
                    } else {
                      const selectPidLabel = this.$refs.editForm.$refs.editPid.selectedLabel
                      this.formPanel.edit.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, selectPidLabel), this.funName]).join('/')
                    }
                  }
                }
              },
              { label: '链接', prop: 'location', placeholder: '输入链接', anchor: 24},
              { label: '排序号', prop: 'orderNo', placeholder: '输入排序号', anchor: 24},
              { label: '是否记日志', prop: 'logFlag', xType: 'switch', anchor: 24, "active-value": 1, "inactive-value": 0},
              // { label: '是否记日志', prop: 'logFlag', xType: 'SelectCode.IF', placeholder: '输入是否记日志', anchor: 24},
              { label: '图标', prop: 'icon', placeholder: '输入图标', anchor: 24},
              { label: '版本', prop: 'version', placeholder: '输入版本', anchor: 24},
              { label: '备注', prop: 'remark', placeholder: '输入备注', anchor: 24},
              { label: '全路径', prop: 'fullPath', anchor: 24, readonly: true, style: 'border: 0;', ref: 'editFunPath',
                on: {
                  'el.form.update': (val, ctx, origin, form) => {// 值,当前组件,关联组件
                    if (form.model.pid) {
                      this.getNodeInfo({funId: form.model.pid}).then(({ success, data }) => {
                        if ( success && data.fullPath) {
                          // 获取上级机构全路径
                          this.fullPath = data.fullPath
                          this.formPanel.edit.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, origin.selectedLabel), form.model.funName]).join('/')
                        }
                      })
                    } else {
                      form.model.fullPath = this.filterArray([form.model.funName]).join('/')
                    }
                  }
                }
              }
            ],
            rules: {
              "funId": [{ required: true, message: '请输入功能编码', trigger: 'blur' }],
              "funName": [{ required: true, message: '请输入功能名称', trigger: 'blur' }],
              "funType": [{ required: true, message: '请输入功能类型', trigger: 'blur' }],
              "orderNo": [{ validator: validateOrderNo, trigger: 'blur' }]
            },
            title: '编辑权限功能',
            type: 'EDIT',
            ref: 'editForm',
            submitBtnList: this.editBtns
          }
        }
      }
    },
    methods: {
      getFrontStr(str, reg) {
        return str.split(reg)[0] + reg
      }
    },
    beforeCreate() {
      // 根据页面路由找出有权限访问的 url 数组
      const urlArr = (this.$route.meta && this.$route.meta.children || []).map(item => item.url)

      // 根据权限 url 数组过滤出能够使用的 按钮数组
      this.addBtns = [
        { label: '保存', methods: 'handleFormAdd', url: '/v1/sys/function/add', icon: 'el-icon-circle-check-outline', type: 'primary', disabled: false }
      ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

      this.editBtns= [
        { label: '保存', methods: 'handleFormEdit', url: '/v1/sys/function/update', icon: 'el-icon-circle-check-outline', type: 'primary', disabled: false }
      ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

      this.treeMenuBtns = [
        { label: '新增', methods: 'handleMenuAdd', url: '/v1/sys/function/add', icon: 'el-icon-circle-plus-outline', type: 'text', action: 'plus' },
        { label: '刷新', methods: 'refresh', url: '/v1/sys/function/findNextChildNodeTree', icon: 'el-icon-refresh', type: 'text' },
        { label: '展开', methods: 'expand', url: '/v1/sys/function/findNextChildNodeTree', icon: 'el-icon-rank', type: 'text' },
        { label: '折叠', methods: 'fold', url: '', icon: 'el-icon-arrow-up', type: 'text' }
      ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

      this.treeOperateBtns = (data) => {
        // 根据 systemType 帅选
        let btnList = []
        !data.systemType
          ? (btnList = [
            { type: 'text', url: '/v1/sys/function/add', icon: 'el-icon-plus', action: 'plus' },
            { type: 'text', url: '/v1/sys/function/deleteNode', icon: 'el-icon-delete', action: 'delete' },
          ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url))
          : (btnList = [
            { type: 'text', url: '/v1/sys/function/add', icon: 'el-icon-plus', action: 'plus' },
            { type: 'text', url: '/v1/sys/function/deleteNode', icon: 'el-icon-remove', action: 'delete' },
          ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url))
        return btnList
      }
    }
  }
</script>

<style lang="scss">
  .function{
    .right{
      .c-button-list{
        justify-content: flex-end;
      }
    }
  }
</style>
